package com.abdu.qrcode;

import android.Manifest;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.BitMatrix;
import com.journeyapps.barcodescanner.BarcodeCallback;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import com.journeyapps.barcodescanner.BarcodeResult;
import com.journeyapps.barcodescanner.CompoundBarcodeView;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    private final Context context = MainActivity.this;
    private static final String TAG = MainActivity.class.getSimpleName();

    private EditText etQRCodeText;
    private ImageView qrcode_image;
    private Button btnCreateQRCode, btnScanQRCode;

    String textToEncode = "";




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initVIew();
        initObject();


    }

    private void initVIew(){
        etQRCodeText = findViewById(R.id.etQRCodeText);
        qrcode_image = findViewById(R.id.qrcode_image);

        btnCreateQRCode = findViewById(R.id.btnCreateQRCode);
        btnCreateQRCode.setOnClickListener(view -> createQRCOde());

        btnScanQRCode = findViewById(R.id.btnScanQRCode);
        btnScanQRCode.setOnClickListener(view -> toScan());
    }

    private void initObject(){

    }

    private void showToast(String text){
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    private void createQRCOde(){
        textToEncode = etQRCodeText.getText().toString();
        if (textToEncode.length()==0) {
            showToast("请输入内容"); return;
        }

        try {
            // 使用 MultiFormatWriter 生成 BitMatrix
            BitMatrix bitMatrix = new MultiFormatWriter().encode(textToEncode, BarcodeFormat.QR_CODE, 800, 800);

            // 使用 BarcodeEncoder 将 BitMatrix 转换为 Bitmap
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);

            // 在 ImageView 中显示生成的二维码
            qrcode_image.setImageBitmap(bitmap);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void toScan(){
        startActivity(new Intent(context, ScanActivity.class));
    }


}